(function ($) {
	var nurData,wardList;
	var perIdStr='@'
	var perArr = []
	var isSelAll = {}
	var prePageId = '', prePageDomId = '',type=''
	var wardId='',nurseid='',perInfo=''
	var start = 0,Limit = 20;
	var pullDom;
	var pulling = false;
	var wardDomId=''
	$.init();
	$.plusReady(function() {
		baseSetup();
	})
	if (!mui.os.plus) {
		baseSetup();
	}
	//获取病区列表
	function getWardList(){
		if (wardList) {
			$('#wardPopo').popover('toggle');
			return
		}
		var pdict = {'nurseid':nurseid}
		var paramDict = {'method':'web.INMDataLimit:FindRoleWardList','params':JSON.stringify(pdict),'type':'RecQuery'}
		//console.log(JSON.stringify(pdict))
		$.DHCWebService(paramDict, function(result) {
			//console.log(JSON.stringify(result))
			wardList = result['data']
			updateWardUL()
		}, function(errorStr) {
			mui.toast('请重试')
		});
	}
	function updateWardUL(){
		var html = ''
		for (var i = 0; i < wardList.length;i++) {
			var oneWard = wardList[i]
			html +='<li data-id="'+oneWard['rw']+'" class="mui-table-view-cell">'+oneWard['WardDesc']+'</li>'
		}
		$('#wardUL')[0].innerHTML = html
		$('#wardPopo').popover('toggle');
		
	}
	
	function changeWard(){
		mui('body input').each(function (index,element) {
			element.blur()
		})
		$('#currWard')[0].innerHTML = this.innerText
		wardId = this.getAttribute('data-id')
		$('#wardPopo').popover('toggle')
		if (!isSelAll[wardId]) {
			$('#selAll')[0].classList.remove('dhc-active');
		}else{
			$('#selAll')[0].classList.add('dhc-active');
		}
		resetKyRefresh()
	}
	//获取病区护士列表
	function getWardNurseList(){
		if (pulling) {
			pullDom.endPullUpToRefresh()
			return;
		}
		pulling = true
		if (wardDomId == 'StandardGroup') {
			FindGroupMemberList()
			return
		}
		var pdict = {'start':start,'limit':Limit,'ward':wardId}
		var method = 'web.INMHRComm:FindWardNurseList'
		if (prePageId == 'teachNewTrain') {
			if (prePageDomId == 'TranCharge') {
				method = 'web.INMDataLimit:FindRoleNurseList'
			}else if (prePageDomId == 'TranNurse') {
				method = 'web.INMDBComm:FindUserList'
			}
			pdict['nurseid'] = nurseid
		}
		var paramDict = {'method':method,'params':JSON.stringify(pdict),'type':'RecQuery'}
		//console.log(JSON.stringify(pdict))
		$.DHCWebService(paramDict, function(result) {
			//console.log(JSON.stringify(result))
			var dataArr = result['data']
			if (!dataArr) {
				pullDom.endPullUpToRefresh();
				pulling = false
				return;
			}
			
			if (start == 0) {
				nurData = dataArr;
			}else{
				nurData = nurData.concat(dataArr)
			}
			updateNurseUL(dataArr)
			if (dataArr.length < Limit) {
				pullDom.endPullUpToRefresh(true);
			}else{
				pullDom.endPullUpToRefresh();
			}
			start += dataArr.length;
			pulling = false
		}, function(errorStr) {
		 	pullDom.endPullUpToRefresh();
		 	pulling = false
		});
	}
	function updateNurseUL(dataArr){
		var nurUL = $('#nurUL')[0];
		if (start == 0) {
			nurUL.innerHTML = ''
		}
		var oldCount = nurUL.querySelectorAll('li').length;
		var idKey = 'Per'
		if (prePageId == 'teachNewTrain') {
			if (prePageDomId == 'TranNurse') {
				idKey = 'rw'
			}
		}
		for (var i = 0; i < dataArr.length;i++) {
			var oneNur = dataArr[i]
			var per = oneNur[idKey]
			var perName = oneNur['PerName']
			var icon = 'square'
			var classStr = 'mui-table-view-cell'
			if (perIdStr.indexOf('@'+per+'@')!= -1) {
				classStr = 'mui-table-view-cell dhc-active'
			}
			if (type == '单选') {
				icon = 'circle'
			}else if(isSelAll[wardId] && perIdStr.indexOf('@'+per+'@') == -1){ //全选
				classStr = 'mui-table-view-cell dhc-active'
				//添加到数组
				var dict = {'per':per,'perName':perName,'ward':wardId,'wardDesc':$('#currWard')[0].innerText}
				perArr.push(dict)
				perIdStr += per+'@'
			}
			
			html = '<div class="'+icon+'"></div>'+
				'<div class="nurName mui-ellipsis">'+perName+'</div>'
			if (oneNur['IsHead'] == 'Y') {
				html += '<div class="nurHead">护士长</div>'
			}else if (wardDomId == 'StandardGroup' && oneNur['MemberPostDesc'] == '组长') {
				html += '<div class="nurHead">组长</div>'
			}
			var newLi = document.createElement('li')
			newLi.setAttribute('class',classStr)
			newLi.innerHTML = html
			newLi.setAttribute('data-id',per)
			newLi.id = 'li-'+(oldCount+i);
			nurUL.appendChild(newLi)
			newLi.addEventListener('tap',selectOneNurse)
		}
	}
	
	function selectOneNurse(){
		var thisDom = this;
		var per = thisDom.getAttribute('data-id')
		var perName = thisDom.querySelector('.nurName').innerText
		var currActive = (thisDom.getAttribute('class').indexOf('dhc-active') != -1)
		if (type == '单选') {
			if (currActive) {
				return
			}
			var oldActive = $('#nurUL .dhc-active')[0]
			if (oldActive) {
				oldActive.classList.remove('dhc-active')
			}
			thisDom.classList.add('dhc-active')
			perArr[0] = {'per':per,'perName':perName,'ward':wardId,'wardDesc':$('#currWard')[0].innerText}
			perIdStr = '@'+per+'@'
			return
		}
		if (!currActive) {
			thisDom.classList.add('dhc-active')
			var dict = {'per':per,'perName':perName,'ward':wardId,'wardDesc':$('#currWard')[0].innerText}
			perArr.push(dict)
			perIdStr += per+'@'
			return
		}
		thisDom.classList.remove('dhc-active')
		for (var i = perArr.length -1 ; i >= 0;i--) {
			if (perArr[i]['per'] == per) {
				perArr.splice(i,1);
				perIdStr.replace('@'+per+'@','@')
				break;
			}
		}
		if (isSelAll[wardId]) {
			$('#selAll')[0].classList.remove('dhc-active')
			isSelAll[wardId] = false;
		}
	}
	function selAllBtnTapped(){
		if (isSelAll[wardId]) {
			isSelAll[wardId] = false
			$('#selAll')[0].classList.remove('dhc-active')
		}else{
			isSelAll[wardId] = true
			$('#selAll')[0].classList.add('dhc-active')
		}
		var lis = $('#nurUL')[0].querySelectorAll('li');
		for (var i = 0; i < lis.length;i++) {
			var liDom = lis[i]
			var per = liDom.getAttribute('data-id')
			var perName = liDom.querySelector('.nurName').innerText;
			if (isSelAll[wardId]) { //全选
				if (liDom.getAttribute('class').indexOf('dhc-active') != -1) {
					continue
				}
				var dict = {'per':per,'perName':perName,'ward':wardId,'wardDesc':$('#currWard')[0].innerText}
				perArr.push(dict)
				perIdStr += per+'@'
				liDom.classList.add('dhc-active')
			}else{
				liDom.classList.remove('dhc-active')
				for (var j = perArr.length -1 ; j >= 0;j--) {
					if (perArr[j]['per'] == per) {
						perArr.splice(j,1);
						perIdStr.replace('@'+per+'@','@')
						break;
					}
				}
			}
		}
	}
	
	function FindGroupMemberList(){
		var todayStr = getDeviceDateStr()
		var pdict = {'parr':wardId+'^'+todayStr}
		var paramDict = {'method':'web.INMSpecialComm:FindMemberList','params':JSON.stringify(pdict),'type':'RecQuery'}
		//console.log(JSON.stringify(pdict))
		$.DHCWebService(paramDict, function(result) {
			//console.log(JSON.stringify(result))
			var dataArr = result['data']
			if (!dataArr) {
				pullDom.endPullUpToRefresh();
				pulling = false
				return;
			}
			updateNurseUL(dataArr)
			pullDom.endPullUpToRefresh(true);
			pulling = false
		}, function(errorStr) {
		 	pullDom.endPullUpToRefresh();
		 	pulling = false
		});
	}
	
	function baseSetup(){
		$('.mui-scroll-wrapper').scroll({
			bounce: true,
			indicators: false, //是否显示滚动条
		});
		perInfo = app.getState()
		nurseid=perInfo['loginID']
		wardId = perInfo['loginWardId']
		$('#currWard')[0].innerHTML = perInfo['loginWardDesc']
		var self = plus.webview.currentWebview()
		prePageId = self.pageId
		prePageDomId = self.domId
		wardDomId = self.wardDomId
		if (self.wardId != undefined) {
			wardId = self.wardId
			$('#currWard')[0].innerHTML = self.wardDesc
		}
		if (prePageId == 'zkNew') {
			document.body.classList.add('singleWard')
		}else if (prePageId == 'teachNewTrain') {
			$('.headWard')[0].style.display = 'none'
			$('#wrapper')[0].style.top = '44px'
		}
		type = self.type
		if (type == '单选') {
			document.body.classList.add('singleType')
		}
		mui('#wardUL').on('tap','li',changeWard) 
		mui('body').on('tap','#closeBtn',mui.back)//关闭按钮
		mui('body').on('tap','#submitBtn',submitBtnTapped)//确定按钮
		mui('body').on('tap','#selWardBtn',getWardList) //获取所有病区列表
		mui('#wardPopo').on('tap','#closePopo',function(){ //病区列表弹框关闭按钮
			$('#wardPopo').popover('toggle');
		});
		mui('body').on('tap','#selAll',selAllBtnTapped); //全选按钮
		var scroll = document.getElementById('scroll');
		pullDom = $(scroll).pullToRefresh({
			up: {
				callback: function() {
					getWardNurseList()
				}
			}
		});
		getWardNurseList();
	}
	
	function submitBtnTapped(){
		var prePage = plus.webview.getWebviewById(prePageId)
		var dataStr = JSON.stringify(perArr)
		prePage.evalJS("selectPerson('"+prePageDomId+"',"+dataStr+")")
		mui.back()
	}
	
	function resetKyRefresh(){
		start = 0;
		nurData = []
		$('#nurUL')[0].innerHTML = '';
		$('#wrapper').scroll().scrollTo(0,0,100);
		if (pullDom) {
			pullDom.refresh(true)
		}
		getWardNurseList();
	}
	function getDeviceDateStr(){
		var currentDate = new Date();
		var cyear = currentDate.getFullYear();
		var cmonth = currentDate.getMonth() + 1;
		var cday = currentDate.getDate();
		var thisDay = cyear + "-" 
		if (cmonth < 10) {
			thisDay +='0'
		}
		thisDay+= cmonth + "-" 
		if (cday < 10) {
			thisDay +='0'
		}
		thisDay += cday;
		return thisDay;
	}
})(mui)
